package com.wjp.dinosaur;

import com.alibaba.fastjson.JSON;
import com.wjp.dinosaur.dao.mapper.UserMapper;
import com.wjp.dinosaur.dao.pojo.User;
import com.wjp.dinosaur.util.UserIdUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import springfox.documentation.schema.Entry;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class ttt {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Test
    public void ooo(){
        Set<String> keys = redisTemplate.keys("ACCOUNT_".concat("*"));
        HashMap<String, String> map = new HashMap<>();

        for (String iterator:keys){
            String id = iterator.substring(8);
            User user = userMapper.selectById(Long.parseLong(id));
            String score = redisTemplate.opsForValue().get(iterator);
            map.put(user.getUserName(),score);
        }

        Map<String, String> stringStringMap = sortMapByValue(map);

        System.out.println(stringStringMap);
    }


    /**
     * 使用 Map按value进行排序
     * @param oriMap
     * @return
     */
    public Map<String, String> sortMapByValue(Map<String, String> oriMap) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }
        Map<String, String> sortedMap = new LinkedHashMap<String, String>();
        List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
                oriMap.entrySet());
        Collections.sort(entryList, new MapValueComparator());

        Iterator<Map.Entry<String, String>> iter = entryList.iterator();
        Map.Entry<String, String> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }

    class MapValueComparator implements Comparator<Map.Entry<String, String>> {
        @Override
        public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
            return o2.getValue().compareTo(o1.getValue());
        }
    }

    @Test
    public void update(){
    }

    @Test
    public void get(){
        String s = redisTemplate.opsForValue().get("ACCOUNT_1552481355082186754");
        System.out.println(s);
    }
}
